package com.push.spider.spider;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.push.common.config.MinioConfig;
import com.push.common.config.TransConfig;
import com.push.common.manager.BeanManager;
import com.push.common.utils.*;
import com.push.common.utils.httpclient.HttpClientResult;
import com.push.common.utils.httpclient.HttpClientUtil;
import com.push.web.domain.BizArticle;
import com.push.web.domain.BizLabelSecond;
import com.push.web.domain.BizSource;
import com.push.web.service.IBizArticleAppendixService;
import com.push.web.service.IBizArticleService;
import com.push.web.service.IBizLabelSecondService;
import com.push.web.service.IBizSourceService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;

public class EuCommissionSpider {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ArrayList<String> hasDownUrls = new ArrayList<>();

    private Queue<String> queue = new LinkedList<String>();

    private BizSource source;

    private List<BizLabelSecond> labelSeconds = new ArrayList<>();

    @Autowired
    IBizArticleService articleService = BeanManager.getBean(IBizArticleService.class);

    @Autowired
    IBizSourceService sourceService = BeanManager.getBean(IBizSourceService.class);

    @Autowired
    IBizLabelSecondService labelSecondService = BeanManager.getBean(IBizLabelSecondService.class);

    @Autowired
    IBizArticleAppendixService articleAppendixService = BeanManager.getBean(IBizArticleAppendixService.class);

    @Autowired
    MinioUtil minioUtil = BeanManager.getBean(MinioUtil.class);

    @Autowired
    MinioConfig prop = BeanManager.getBean(MinioConfig.class);

    @Autowired
    private TransConfig transConfig = BeanManager.getBean(TransConfig.class);

    public int size = 0;

    public EuCommissionSpider(String sourceId) {
        this.source = sourceService.selectBizSourceBySourceId(Long.valueOf(sourceId));
        this.labelSeconds = labelSecondService.selectBizLabelSecondListByParentIds(this.source.getLabelIds());
    }

    @SneakyThrows
    public void run(){
        HashMap params = new HashMap();
        params.put("language","en");
        params.put("documenttype","291");
        params.put("pagesize","10");
        params.put("pagenumber","1");
        HttpClientResult clientResult = HttpClientUtil.doGet("https://ec.europa.eu/commission/presscorner/api/search", params,true);
        JSONObject resultObj = JSONObject.parseObject(clientResult.getContent());
        JSONArray jsonArray = resultObj.getJSONArray("docuLanguageListResources");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject articleObj = jsonArray.getJSONObject(i);
            String title = articleObj.getString("title");
            String leadText = articleObj.getString("leadText");
            String eventDate = articleObj.getString("eventDate");
            HashMap documentsParams = new HashMap();
            params.put("reference",articleObj.getString("refCode"));
            params.put("language","en");
            HttpClientResult documentsResult = HttpClientUtil.doGet("https://ec.europa.eu/commission/presscorner/api/documents", documentsParams,true);
            JSONObject documentsObj = JSONObject.parseObject(clientResult.getContent());
            String htmlContent = documentsObj.getJSONObject("docuLanguageResource").getString("htmlContent");
            String dataKey = EncryptUtil.encrypt(articleObj.getString("refCode"), "md5");
            String sourceUrl = "https://ec.europa.eu/commission/presscorner/detail/en/"+articleObj.getString("refCode").toLowerCase(Locale.ROOT).replaceAll("/","_");
            BizArticle article = buildArticle(dataKey, title, leadText, sourceUrl, eventDate, htmlContent, source.getSourceId());
            BizArticle bizArticle = articleService.selectBizArticleByDataKey(dataKey);
            if (StringUtils.isNull(bizArticle)){
                if (strContains(article.getTitleOrg(), labelSeconds)){
                    //自动翻译标题
                    if (StringUtils.isContainsChinese(article.getTitleOrg())){
                        article.setTitleCn(article.getTitleOrg());
                    } else {
                        String transWord = getTransResult(article.getTitleOrg(), "auto", "zh");
                        JSONObject titleObj = JSONObject.parseObject(transWord);
                        JSONArray titleArray = titleObj.getJSONArray("trans_result");
                        if (StringUtils.isNotNull(titleArray) && titleArray.size() > 0){
                            article.setTitleCn(titleArray.getJSONObject(0).getString("dst"));
                        }
                    }

                    //自动翻译摘要
                    if(transConfig.isAbstractTrans() && StringUtils.isNotEmpty(article.getSummaryOrg())){
                        String transWord = getTransResult(article.getSummaryOrg(), "auto", "zh");
                        JSONObject titleObj = JSONObject.parseObject(transWord);
                        JSONArray titleArray = titleObj.getJSONArray("trans_result");
                        if (StringUtils.isNotNull(titleArray) && titleArray.size() > 0){
                            article.setSummaryCn(titleArray.getJSONObject(0).getString("dst"));
                        }
                    }
                    articleService.insertBizArticle(article);
                }
            } else {
                article.setId(bizArticle.getId());
                articleService.updateBizArticle(article);
            }
            size++;
            Thread.sleep(source.getIntervalNum()*1000);
        }
    }
    public BizArticle buildArticle(String dataKey, String titleOrg, String summaryOrg, String url,String publishTime, String contentOrg, long sourceId){
        BizArticle article = new BizArticle();
        article.setDataKey(dataKey);
        article.setTitleOrg(titleOrg);
        article.setUrl(url);
        article.setSummaryOrg(summaryOrg);
        article.setContentsOrg(contentOrg);
        article.setContentsCn(StringUtils.delHtmlTags(contentOrg));
        article.setPublishTime(publishTime);
        article.setPublishFormatTime(DateUtils.formatDate(DateUtils.parseDate(publishTime),publishTime));
        article.setSourceId(sourceId);
        article.setCreateTime(DateUtils.getNowDate());
        return article;
    }

    public static boolean strContains(String str, List<BizLabelSecond> labels){
        if (labels == null){
            return true;
        }
        if (labels.isEmpty()){
            return true;
        }
        if(StringUtils.isEmpty(str)){
            return false;
        }
        long len = labels.parallelStream().filter(label -> str.toLowerCase(Locale.ROOT).contains(label.getLabelName().toLowerCase(Locale.ROOT))).count();
        if (len > 0){
            return true;
        }
        return false;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpClientUtil.doGet(transConfig.getTransUrl(), params,false).getContent();
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", transConfig.getAppid());
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = transConfig.getAppid() + query + salt + transConfig.getSecurityKey();
        params.put("sign", MD5.md5(src));
        return params;
    }

    public int getSize(){
        return size;
    }
}
